package com.jelly.mina.chat;

import java.net.InetSocketAddress;
import java.security.GeneralSecurityException;

import org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder;
import org.apache.mina.example.echoserver.ssl.BogusSslContextFactory;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.filter.logging.MdcInjectionFilter;
import org.apache.mina.filter.ssl.SslFilter;
import org.apache.mina.transport.socket.SocketAcceptor;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;

public class Main {
	/** 服务器端口号 */
	private static final int PORT = 1234;
	/** 是否启用ssl */
	private static final boolean USE_SSL = false;

	public static void main(String[] args) throws Exception {
		// 实例化一个NioSocketAcceptor
		SocketAcceptor acceptor = new NioSocketAcceptor();
		// 获取过滤器链
		DefaultIoFilterChainBuilder chain = acceptor.getFilterChain();
		// 实例化MdcInjectionFilter过滤器,针对日志输出做MDC操作,可以参考log4j的MDC、NDC的文档
		MdcInjectionFilter mdcInjectionFilter = new MdcInjectionFilter();
		// 添加MdcInjectionFilter过滤器
		chain.addLast("mdc", mdcInjectionFilter);
		// 如果开启ssl,则添加ssl支持过滤链
		if (USE_SSL) {
			addSSLSupport(chain);
		}
		/*
		 * 添加TextLine编解码过滤器,将一行以换行符为结束符号的byte[]转换成String对象
		 * TextLineCodecFactory有TextLineEncoder编码实现,TextLineDecoder解码实现
		 */
		chain.addLast("code", new ProtocolCodecFilter(
				new TextLineCodecFactory()));
		 //添加日志过滤器  
		addLogger(chain);
		 // 设置handler  
		acceptor.setHandler(new ChatProtocolHandler());
		 //绑定服务器端口  
		acceptor.bind(new InetSocketAddress(PORT));
	}

	/**
	 * 添加支持ssl过滤器
	 * 
	 * @param chain
	 * @throws GeneralSecurityException
	 */
	private static void addSSLSupport(DefaultIoFilterChainBuilder chain)
			throws GeneralSecurityException {
		SslFilter sslFilter = new SslFilter(
				BogusSslContextFactory.getInstance(true));
		chain.addLast("sslFilter", sslFilter);
		System.out.println("SSL ON");
	}

	/**
	 * 添加日志过滤器
	 * 
	 * @param chain
	 */
	private static void addLogger(DefaultIoFilterChainBuilder chain) {
		chain.addLast("logger", new LoggingFilter());
		System.out.println("Logging On");
	}
}
